<template>
  <div>
    <!--查询-->
    <el-card style="">
      <el-row :gutter="20">
        <el-col :span="1.5">
          <el-cascader
            clearable
            :props="props"
            v-model="positionArr"
            @change="gradeUnitChange"
            popper-class="pc-sel-area-cascader"
            style="width: 470px"
          >
          </el-cascader>
        </el-col>
        <el-col :span="10">
          <el-popover placement="top" width="200" ref="importVisible">
            <p>只能以模板文件上传，否则服务器不识别！！</p>
            <div class="clearfix">
              <el-button
                size="mini"
                class="left"
                type="primary"
                @click="downloadBtn"
                >下载模板</el-button
              >
              <el-upload
                class="upload-demo"
                action=""
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :limit="1"
                accept="application/vnd.openxmlformats-    
        officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                :auto-upload="true"
              >
                <el-button type="success" size="mini">上传至服务器</el-button>
              </el-upload>
            </div>
          </el-popover>
          <el-button
            style="margin-left=20px"
            v-show="!timeShow"
            v-popover:importVisible
            type="info"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5" :push="10">
          <el-button
            v-show="timeShow"
            @click="editBtn"
            type="primary"
            style="width: 360%"
            >编辑</el-button
          >
        </el-col>

        <el-col :span="1.5">
          <el-button v-show="!timeShow" @click="saveBtn" type="primary"
            >保存</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button v-show="!timeShow" @click="quitBtn" type="warning"
            >取消</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-show="!timeShow"
            @click="delBtn"
            type="danger"
            :disabled="delDisable"
            >删除</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <el-card
      ><span v-if="belongName != ''" class="title">{{ belongName }}课程表</span>
      <span v-else class="title">请选择要查看的班级</span></el-card
    >

    <!--表格-->
    <!-- <el-card v-show="belongName != ''"> -->
    <el-card>
      <!-- <el-table :data="timeData" stripe style="width: 100%" v-show="show"> -->
      <el-table :data="timeData" stripe style="width: 100%">
        <el-table-column
          label="周"
          fixed="left"
          prop="label"
          align="center"
        ></el-table-column>

        <el-table-column label="上午" align="center">
          <el-table-column
            v-for="(v, i) in titleData"
            :key="i"
            v-if="v.label === '上午'"
            align="center"
          >
            <template slot="header" slot-scope="scope">
              <div class="tabletitle-timeline">
                第{{ v.count }}节 <br />
                {{ v.startTime }}-{{ v.endTime }}
              </div>
            </template>
            <template slot-scope="scope">
              <div>
                <div v-if="timeShow">
                  {{ scope.row[sbjectKey[i]] }}<br />
                  {{ scope.row[teacherKey[i]] }}
                </div>
                <div v-else>
                  <el-select
                    clearable
                    @clear="scope.row[teacherKey[i]] = ''"
                    @change="
                      handleUpdate(scope.row[sbjectKey[i]], scope.row, i)
                    "
                    v-model="scope.row[sbjectKey[i]]"
                    size="mini"
                    placeholder="科目"
                  >
                    <el-option
                      v-for="val in subjects"
                      :key="val.subjectId"
                      :label="val.subjectName"
                      :value="val.subjectName"
                    ></el-option>
                  </el-select>
                  <el-select
                    clearable
                    v-if="
                      scope.row[sbjectKey[i]]
                        ? (disable = true)
                        : (disable = false)
                    "
                    v-model="scope.row[teacherKey[i]]"
                    @click.native="
                      handleSchool(scope.row[sbjectKey[i]], scope.row, i)
                    "
                    size="mini"
                    placeholder="任课老师"
                  >
                    <el-option
                      v-for="val in teachers"
                      :key="val.userId"
                      :label="val.userName"
                      :value="val.userName"
                    ></el-option>
                  </el-select>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="下午" align="center">
          <el-table-column
            v-for="(v, i) in titleData"
            :key="i"
            v-if="v.label === '下午'"
            align="center"
          >
            <template slot="header" slot-scope="scope">
              <div class="tabletitle-timeline">
                第{{ v.count }}节 <br />
                {{ v.startTime }}-{{ v.endTime }}
              </div>
            </template>
            <template slot-scope="scope">
              <div>
                <div v-if="timeShow">
                  {{ scope.row[sbjectKey[i]] }}<br />
                  {{ scope.row[teacherKey[i]] }}
                </div>
                <div v-else>
                  <!-- <el-input
                  size="mini"
                  placeholder="科目"
                  suffix-icon="el-icon-date"
                  v-model="scope.row[sbjectKey[i]]"
                >
                </el-input> -->
                  <el-select
                    clearable
                    @clear="scope.row[teacherKey[i]] = ''"
                    @change="
                      handleUpdate(scope.row[sbjectKey[i]], scope.row, i)
                    "
                    v-model="scope.row[sbjectKey[i]]"
                    size="mini"
                    placeholder="科目"
                  >
                    <el-option
                      v-for="val in subjects"
                      :key="val.subjectId"
                      :label="val.subjectName"
                      :value="val.subjectName"
                    ></el-option>
                  </el-select>
                  <el-select
                    clearable
                    v-if="
                      scope.row[sbjectKey[i]]
                        ? (disable = true)
                        : (disable = false)
                    "
                    v-model="scope.row[teacherKey[i]]"
                    size="mini"
                    placeholder="任课老师"
                  >
                    <el-option
                      @click.native="
                        handleSchool(scope.row[sbjectKey[i]], scope.row, i),
                          scope.row
                      "
                      v-for="val in teachers"
                      :key="val.userId"
                      :label="val.userName"
                      :value="val.userName"
                    ></el-option>
                  </el-select>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {
  studentClass,
  getTeacher,
  getSubject,
  addCourse,
  listClassCourse,
  delCourse,
} from "@/api/class/roster";
// import {auth} from '../../lib/auth';

export default {
  data() {
    return {
      openUpdate: false,
      //级联的班级
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          let parentId;
          if (node.value) {
            parentId = node.value;
          } else {
            parentId = 0;
          }
          studentClass({ parentId: parentId }).then((res) => {
            const nodes = res.data.map((v) => ({
              value: v.deptId,
              label: v.typeName,
              leaf: level === 1,
            }));
            resolve(nodes);
          });
        },
      },
      delDisable: false,
      pageButton: {}, //权限按钮
      //年级班级数据
      positionArr: [], //级联选择值
      show: false,
      timeShow: true, //编辑表与展示表
      teachers: [], //全部教师
      subjects: [],
      userInfo: [],
      sbjectKey: ["oneS", "twoS", "threeS", "fourS", "fiveS", "sixS"], //科目key值
      teacherKey: ["oneT", "twoT", "threeT", "fourT", "fiveT", "sixT"], //老师key值
      //每天的课表
      timeData: [
        {
          id: "1",
          label: "周一",
        },
        {
          id: "2",
          label: "周二",
        },
        {
          id: "3",
          label: "周三",
        },
        {
          id: "4",
          label: "周四",
        },
        {
          id: "5",
          label: "周五",
        },
      ],
      belongName: "", //班级名
      belongId: "", //班级id
      //课节数据---标题
      titleData: [
        {
          id: "1",
          count: 1,
          label: "上午",
          startTime: "08:25",
          endTime: "09:05",
        },
        {
          id: "2",
          count: 2,
          label: "上午",
          startTime: "09:15",
          endTime: "09:55",
        },
        {
          id: "3",
          count: 3,
          label: "上午",
          startTime: "10:10",
          endTime: "10:50",
        },
        {
          id: "4",
          count: 4,
          label: "上午",
          startTime: "11:00",
          endTime: "11:40",
        },
        {
          id: "5",
          count: 5,
          label: "下午",
          startTime: "14:40",
          endTime: "15:20",
        },
        {
          id: "6",
          count: 6,
          label: "下午",
          startTime: "15:30",
          endTime: "16:10",
        },
      ],
    };
  },
  mounted() {
    this.timetableLoad();
  },
  methods: {
    handleSchool(school, data, id) {
      console.log(data.id);
      console.log(id + 1);
      console.log(this.belongName);
      getTeacher(school, data.id, id + 1, this.belongName).then((res) => {
        this.teachers = res.data;
      });
    },
    handleUpdate(subjectName, data, id) {
      //全部教师
      console.log(data.id);
      console.log(id + 1);
      console.log(this.belongName);
      if (subjectName != "") {
        getTeacher(subjectName, data.id, id + 1, this.belongName).then(
          (res) => {
            this.teachers = res.data;
          }
        );
      }
    },

    timetableLoad() {
      // //根据path来找页面权限，按钮根据code来找对应的按钮权限
      // let self = this;
      // this.pageButton=auth.allButtons();
      // auth.getButtons(this.$route.name).forEach(function (val) {
      //   self.pageButton[val.code]=true;
      // });
    },
    //获取课程名称
    getTimeTableFind() {
      getSubject().then((res) => {
        this.subjects = res;
      });
    },
    //获取班级课程表
    listClassCourse() {
      listClassCourse(this.belongId).then((res) => {
        this.timeData = res;
        if (res.length < 1) {
          this.timeData = [
            {
              id: "1",
              label: "周一",
            },
            {
              id: "2",
              label: "周二",
            },
            {
              id: "3",
              label: "周三",
            },
            {
              id: "4",
              label: "周四",
            },
            {
              id: "5",
              label: "周五",
            },
          ];
        }
      });
    },

    //获取年级班级级联
    gradeUnitChange(val) {
      // console.log(val);
      if (val.length > 1) {
        this.timeShow = true;
        this.belongId = val[val.length - 1];
        this.listClassCourse();
        studentClass({ deptId: this.belongId }).then((res) => {
          this.belongName = res.data[0].typeName;
        });
      } else {
        this.timeShow = true;
        this.belongId = "";
        this.belongName = "";
        this.timeData = [
          {
            id: "1",
            label: "周一",
          },
          {
            id: "2",
            label: "周二",
          },
          {
            id: "3",
            label: "周三",
          },
          {
            id: "4",
            label: "周四",
          },
          {
            id: "5",
            label: "周五",
          },
        ];
      }
      // if (this.belongId) {
      //   this.show = true;
      // } else {
      //   this.show = false;
      // }
    },

    //保存
    saveBtn() {
      this.timeData.forEach((value, index) => {
        value["classId"] = this.belongId;
      });
      console.log(this.timeData);
      addCourse(this.timeData).then((res) => {
        console.log(res);
      });
      this.timeShow = true;
    },
    //取消
    quitBtn() {
      listClassCourse(this.belongId).then((res) => {
        this.timeData = res;
        if (res.length < 1) {
          this.timeData = [
            {
              id: "1",
              label: "周一",
            },
            {
              id: "2",
              label: "周二",
            },
            {
              id: "3",
              label: "周三",
            },
            {
              id: "4",
              label: "周四",
            },
            {
              id: "5",
              label: "周五",
            },
          ];
        }
      });
      this.timeShow = true;
    },
    //编辑
    editBtn() {
      this.openUpdate = true;
      this.delDisable = false;
      let self = this;
      this.getTimeTableFind();
      if (this.belongId != "") {
        listClassCourse(this.belongId).then((res) => {
          if (res.length == 0) {
            this.delDisable = true;
          }
        });
      }

      if (this.belongId !== "") {
        this.timeShow = false;
      } else {
        this.$message({ type: "warning", message: "请先选择对应班级" });
      }
    },
    //删除课表
    delBtn() {
      this.$confirm("是否删除当前整张课表?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
        center: true,
      }).then(() => {
        let self = this;
        if (this.belongId !== undefined && this.belongId !== "") {
          delCourse(this.belongId);
          this.timeData = [
            {
              id: "1",
              label: "周一",
            },
            {
              id: "2",
              label: "周二",
            },
            {
              id: "3",
              label: "周三",
            },
            {
              id: "4",
              label: "周四",
            },
            {
              id: "5",
              label: "周五",
            },
          ];
          this.$message({
            type: "success",
            message: "删除" + this.belongName + "课程表成功",
          });
          setTimeout(() => {
            this.timeShow = true;
          }, 2000);
        } else {
          this.$message({ type: "warning", message: "请联系管理员" });
        }
      });
    },
    //导入
    downloadBtn() {
      // requestServices.timeTableDownload().then((res) => {
      //   let url = res.resultData;
      //   let link = document.createElement("a");
      //   link.style.display = "none";
      //   link.href = url;
      //   link.setAttribute("id", "downloadLink");
      //   link.setAttribute("download", "模板.xls");
      //   document.body.appendChild(link);
      //   link.click();
      //   // 删除添加的a链接
      //   let objLink = document.getElementById("downloadLink");
      //   document.body.removeChild(objLink);
      // });
    },
    importBtn(file) {
      if (!this.belongId) {
        this.$message({ type: "warning", message: "请先选择教室或者班级" });
        return false;
      }
      // console.log(file);
      //   const isXls = file.type === "application/vnd.ms-excel";
      //   const isXlsx =
      //     file.type ===
      //     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

      //   if (!isXls && !isXlsx) {
      //     this.$message("上传格式不正确，请确认上传文件后缀名为.xls或.xlsx");
      //     return false;
      //   } else {
      //     let importFd = new FormData();
      //     importFd.append("importFile", file);
      //     importFd.append("belongId", this.belongId);
      //     // importFd.append("belongType", this.belongType);
      //     requestServices.timeTableImport(importFd).then((res) => {
      //       this.$message("文件已上传至服务器");
      //     });
      //   }
    },
    //上传文件时处理方法
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    importfxx(obj) {
      let that = this;
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];

      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          that.timeData = outdata;
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          // let arr = [];
          // outdata.map((v) => {
          //   let obj = {};
          //   obj.code = v["Code"];
          //   obj.name = v["Name"];
          //   obj.pro = v["province"];
          //   obj.cit = v["city"];
          //   obj.dis = v["district"];
          //   arr.push(obj);
          // });
          // _this.da=arr;
          // _this.dalen=arr.length;
          // return arr;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.tabletitle-timeline {
  line-height: 18px !important;
}
.el-card.is-always-shadow {
  margin: 20px;
}
.el-dialog__header {
  text-align: center;
}
.span {
  margin-top: 2% !important;
  margin-left: 48% !important;
}
.title {
  text-align: center;
  display: block;
  font-weight: bold;
}
.el-cascader-menu__list {
  width: 236px;
}
.pc-sel-area-cascader[x-placement^="bottom"] {
  // 选择器面板与输入框的距离
  margin-top: 1px !important;
}

.pc-sel-area-cascader {
  /* // 选择面板样式 */
  // .el-cascader-panel {
  //   width: 543px;
  // }
  // .el-cascader-menu__wrap {
  //   /* // 设置选择器省市区分块面板高度 */
  //   height: 200px;
  // }
  .el-cascader-menu {
    /* // 省市区分块右边框 */
    border: none;
  }
  .el-scrollbar__thumb {
    /* // 上下滚动条 */
    display: none;
  }
  .el-cascader-node {
    height: 40px;
  }
  .el-cascader-node:hover {
    /* // 设置鼠标滑过时文字颜色 */
    color: #4e5ef1;
  }
  .el-cascader-node__label {
    /* // 设置文字样式 */
    padding: 0 7px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
  }
  /* // 文字选中样式及span背景颜色 */
  .el-cascader-node.in-active-path,
  .el-cascader-node.is-active,
  .el-cascader-node.is-selectable.in-checked-path {
    color: #4e5ef1;
  }
  .el-icon-check {
    /* // 去掉选中小对勾 */
    display: none;
  }
  .el-icon-arrow-right {
    /* // 选项去掉右侧小图标 */
    display: none;
  }
  /* // 选择器面板边框及圆角设置 */
  border-radius: 12px !important;
  border: 1px solid #f6f7f8 !important;
  box-shadow: 0px 10px 40px 0px rgba(0, 0, 0, 0.07) !important;
}
.pc-sel-area-cascader[x-placement^="bottom"] {
  /* // 选择器面板与输入框的距离 */
  margin-top: 1px !important;
}
.pc-sel-area-cascader[x-placement^="bottom"] .popper__arrow {
  /* // 输入框下面小三角形 */
  display: none;
}
</style>
